package com.example.myapplication.util;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.example.myapplication.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Network {
//    public static String BASE_KEY = "a77f95ab10260a54ef8dd502427a3181";
    public static String BASE_KEY = "cb53bd41a74ef445a2d1b7fcfebe6fa0";
    private static String BASE_URL  = "http://v.juhe.cn/toutiao/";

    //线程池
    private static final ExecutorService executor = Executors.newCachedThreadPool();
    //Handler是Android SDK来处理异步消息的核心类。
    //子线程与主线程通过Handler来进行通信。子线程可以通过Handler来通知主线程进行UI更新。
    private static final Handler mainHandler = new Handler(Looper.getMainLooper());

    public static Map<String, String> getNewsSortList(){
        Map<String, String> map = new HashMap<>();
        map.put("推荐","top");
        map.put("国内","guonei");
        map.put("国际","guoji");
        map.put("娱乐","yule");
        map.put("体育","tiyu");
        map.put("军事","junshi");
        map.put("科技","keji");
        map.put("财经","caijing");
        map.put("游戏","youxi");
        map.put("汽车","qiche");
        map.put("健康","jiankang");
        return map;
    }

    // GET 请求
    public static void doGet(Context context ,String path, OkResult callback) {
        executor.execute(() -> {
            HttpURLConnection connection = null;
            try {
                URL url = new URL(BASE_URL + path + BASE_KEY);
                Log.d("doGet", "doGet:url = " + url);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                //告诉客户端实际返回的内容的内容类型
                connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
                //指定希望接收的内容类型
                connection.setRequestProperty("Accept", "application/json");

                int responseCode = connection.getResponseCode();
                Log.d("Network", "请求返回码：: " + responseCode);

                if (responseCode == HttpURLConnection.HTTP_OK) {
                    String response = readStream(connection.getInputStream());
                    notifySuccess(response, callback);
                } else {
                    notifyError("请求返回码：: " + responseCode, callback);
                }
            } catch (IOException e) {
                notifyError("请求错误: " + e.getMessage(), callback);
            } finally {
                //释放资源
                if (connection != null) connection.disconnect();
            }
        });
    }



    // 读取响应流
    private static String readStream(InputStream inputStream) throws IOException {
        StringBuilder response = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(inputStream, "UTF-8"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        }
        return response.toString();
    }



    // 主线程回调成功
    private static void notifySuccess(String response, OkResult callback) {
        mainHandler.post(() -> {
            try {
                callback.success(new JSONObject(response));
            } catch (JSONException e) {
                Log.e("Network", "请求错误", e);
                callback.error("请求错误");
            }
        });
    }

    // 主线程回调失败
    private static void notifyError(String message, OkResult callback) {
        mainHandler.post(() -> callback.error(message));
    }

    // 回调接口
    public interface OkResult {
        void success(JSONObject result);
        void error(String message);
    }
}


